package lookas.utils;

import java.util.Collection;
import java.util.Collections;

import javax.annotation.Resource;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

public class SecurityUtils {

    private static Log           log = LogFactory.getLog(SecurityUtils.class);

    private static SecurityUtils instance;

    private SecurityUtils() {
    }

    @Resource(name = "securityUtils")
    void setInstance(SecurityUtils instance) {
        SecurityUtils.instance = instance;
    }

    public static SecurityUtils getInstance() {
        return instance;
    }

    public Collection<GrantedAuthority> getPrincipalAuthorities() {
        Authentication currentUser = SecurityContextHolder.getContext().getAuthentication();

        if (null == currentUser) {
            return Collections.emptyList();
        }

        if ((null == currentUser.getAuthorities()) || (currentUser.getAuthorities().size() < 1)) {
            return Collections.emptyList();
        }

        Collection<GrantedAuthority> granted = currentUser.getAuthorities();

        log.debug(currentUser.getName());
        log.debug(granted);
        return granted;
    }

    public boolean getPrincipalAuthorities(String role) {
        if (role == null)
            return false;
        Collection<GrantedAuthority> auth = getPrincipalAuthorities();
        for (GrantedAuthority a : auth) {
            if (role.equals(a.getAuthority()))
                return true;
        }
        return false;
    }
}
